<script setup>
import {ref,onMounted} from 'vue'
import axios from 'axios'
import {ElMessage,ElMessageBox} from 'element-plus'
import qs from "qs";
import {format} from "date-fns";
const input = ref('')
function formatTimestamp(timestamp) {
    return format(new Date(timestamp), 'yyyy-MM-dd HH:mm:ss');
}
//分页
// const tableData = ref([]); // 当前页的数据列表
const total = ref(0); // 总记录数
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示的记录数

function fetchData(page) {
    // 发送请求到后端获取数据

    axios({
        method:"post",
        url: 'http://localhost:8080/admin/getGoodList',
        data: {"currentpage":page},
        transformRequest: [ function(data){
            return qs.stringify(data)  //使用Qs将请求参数序列化
        }],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'  //必须设置传输方式
        }
    }).then(response => {
        tableData.value = [];
        total.value = response.data.total;
        // currentPage.value = response.data.pageNum;
        response.data.list.forEach(item => {
            tableData.value.push(item);
        });
        // tableData.value = response.data.list;

    })
        .catch(error => {
            console.error("Error fetching data:", error);
        });
};

function handlePageChange(newPage){
    currentPage.value = newPage;
    fetchData(newPage);
};
//表格数据
const tableData =ref([])
function getAll(){
  axios({
    method:"get",
    url:"http://localhost:8080/admin/getGoodList"
  }).then((response)=>{
    tableData.value=response.data
  }).catch((error)=>{
    console.log(error);
  })
}
fetchData(1); // 初始加载第一页数据

// 商品类别
const options = ref({
      gtid:'',
      gtname:'',
}

);
//邮寄方式
const soptions = ref([

  {
    label:'包邮',
    value:'包邮'
  },
  {
    label:'不包邮',
    value:'不包邮'
  },
]); // 邮寄方式


// 审核状态选项
const statusoptions = ref([
  {
    label:'审核中',
    value:'审核中'
  },
  {
    label:'审核通过',
    value:'审核通过'
  },
  {
    label:'审核失败',
    value:'审核失败'
  },

]);

function getCategories() {
  axios.post('http://localhost:8080/admin/goodtypelist').then((response) => {
    options.value = response.data; // 假设返回的数据已经是选项数组
  }).catch((error) => {
    console.error('获取商品类别数据失败:', error);
  });
}


onMounted(() => {
   // getAll();
   getCategories();
   fetchData(1); // 初始加载第一页数据

});

// 搜索参数
const searchParams = ref({
  gtid: '',
  gname:'',
  minAmount: '',
  maxAmount: '',
  sloginname: '',
  send:'',
  status: '',
  currentPage:''
});

// 同意订单
function agreeOrder(gid) {
  ElMessageBox.confirm('确定要同意这个商品的审核请求吗？', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    axios({
      method: 'post',
      url: `http://localhost:8080/admin/succeedGoods`,
      data: { gid: gid, status: '审核成功' },
    }).then((response) => {
      if (response.data === 1) {
        ElMessage({
          type: 'success',
          message: '同意成功'
        });
        fetchData(1); // 初始加载第一页数据
      } else {
        ElMessage({
          type: 'error',
          message: '同意失败'
        });
      }
    }).catch(() => {
      ElMessage({
        type: 'error',
        message: '同意请求失败'
      });
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消操作'
    });
  });
}

// 拒绝订单
function rejectOrder(gid) {
  ElMessageBox.confirm('确定要拒绝这个商品的审核请求吗？', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    axios({
      method: 'post',
      url: `http://localhost:8080/admin/failGoods`,
      data: { gid: gid, status: '审核失败' },
    }).then((response) => {
      if (response.data === 1) {
        ElMessage({
          type: 'success',
          message: '拒绝成功'
        });
        fetchData(1); // 初始加载第一页数据
      } else {
        ElMessage({
          type: 'error',
          message: '拒绝失败'
        });
      }
    }).catch(() => {
      ElMessage({
        type: 'error',
        message: '拒绝请求失败'
      });
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消操作'
    });
  });
}

// 处理搜索事件
function handleSearch() {
  searchParams.value.currentPage=currentPage.value;
  const formData = new URLSearchParams(searchParams.value);
  axios({
    url:"http://localhost:8080/admin/getGoodMoHuList",
    method:"post",
    data:formData,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded' // 设置正确的请求头
    }
  }).then((response) => {
    tableData.value = response.data.list; // 假设返回的数据已经是选项数组
  }).catch((error) => {
    console.error('查询失败:', error);
    ElMessage.error('查询失败');

  });


}
const value=ref();
//删除商品
function deleteGoods(gid){

    ElMessageBox.confirm(
        "请确定是否要删除","提示",
        {   confirmButtonText:"确定",cancelButtonText:"取消",type:'warning' }
    ).then(()=>{
        console.log("删除");
        axios({
            method:"post",
            url:"http://localhost:8080/admin/delGood",
            data:{"gid":gid},
            transformRequest: [ function(data){
                return qs.stringify(data)  //使用Qs将请求参数序列化
            }],
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'  //必须设置传输方式
            }

        }).then((response)=>{
            if(response.data===1){
                fetchData(1); // 初始加载第一页数据
                ElMessage({ type:'success',  message:"下架成功" })
            }else{
                fetchData(1); // 初始加载第一页数据
                ElMessage({ type:'error', message:"该商品还未上架"  })
            }
        })
    }).catch(()=>{
        ElMessage({
            type:'info',
            message:"取消删除"
        })
    })
}

function handleDelete(gid) {
    alert(2)
    axios({
        method: "post",
        url: "http://localhost:8080/admin/delGood",
        data: { "gid": gid },
        transformRequest: [function (data) {
            return qs.stringify(data); // 使用Qs将请求参数序列化
        }],
    }).then((response) => {
        if (response.data === 1) {
            ElMessage({
                type: 'success',
                message: '下架成功',
            });
            fetchData(1); // 初始加载第一页数据
        } else {
            ElMessage({
                type: 'error',
                message: '删除失败',
            });
            fetchData(1); // 初始加载第一页数据
        }
    }).catch((error) => {
        ElMessage({
            type: 'error',
            message: '请求失败',
        });
        console.error("Error during deletion:", error);
    });
}

</script>

<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card style="max-width: 100%">

          <!-- 查询 -->
          <el-row>
            <el-col :span="3">
              <el-select v-model="searchParams.gtid" clearable placeholder="请选择商品类别" style="width: 150px">
                <el-option v-for="item in options" :key="item.value" :label="item.gtname" :value="item.gtid"/>
              </el-select>
            </el-col>
            <el-col :span="3">
              <el-select v-model="searchParams.send" clearable placeholder="请选择邮寄方式" style="width: 150px">
                <el-option v-for="item in soptions" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-col>
            <el-col :span="3">
              <el-select v-model="searchParams.status" clearable placeholder="请选择审核状态" style="width: 150px">
                <el-option v-for="item in statusoptions" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-col>
            <el-col :span="3">
                <el-input v-model="searchParams.gname" placeholder="请输入商品名称" style="width: 150px"/>
            </el-col>
            <el-col :span="3">
              <el-input v-model="searchParams.minAmount" placeholder="最低金额" style="width: 150px"/>
            </el-col>
            <el-col :span="3">
              <el-input v-model="searchParams.maxAmount" placeholder="最高金额" style="width: 150px"/>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="handleSearch" class="searchbtn">
                <el-icon class="icon-search"><Search /></el-icon>查询
              </el-button>
            </el-col>
            <el-divider />
          </el-row>


            <!-- 表格 -->
            <el-table :data="tableData" border style="width: 100%">
                <el-table-column prop="gid" label="商品Id" width="100" align="center" />
                <el-table-column prop="gname" label="商品名称" width="100" align="center" />
                <el-table-column prop="sloginname" label="卖家账号" width="100" align="center" />
                <el-table-column prop="gimage" label="商品图片" width="100" align="center" >
                  <template #default="scope">
                    <el-image style="width: 100px; height: 100px" :src="scope.row.gimage"></el-image>
                  </template>
                </el-table-column>
                <el-table-column prop="gtid" label="类别" width="100" align="center" />
              <el-table-column prop="price" label="商品价格" width="100" align="center" />
              <el-table-column prop="send" label="邮寄方式" width="100" align="center" />
              <el-table-column prop="description" label="商品描述" width="100" align="center" />
                <el-table-column prop="status" label="审核状态" width="100" align="center" >
                  <template #default="scope">
                    <!-- 使用三元运算符来判断审核状态，并设置不同的类型 -->
                    <el-tag :type="scope.row.status === '审核通过' ? 'success' : (scope.row.status === '审核失败' ? 'danger' : 'warning')">
                      {{ scope.row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="sum" label="库存" width="100" align="center" />
                <el-table-column prop="uptime" label="上架时间" width="100" align="center" >
                    <template #default="scope">
                        <span v-if="scope.row.uptime">{{ formatTimestamp(scope.row.uptime) }}</span>
                        <span v-else>未上架</span>
                    </template>
                </el-table-column>
                <el-table-column prop="downtime" label="下架时间" width="100" align="center" >
                        <template #default="scope">
                <span v-if="scope.row.downtime">
                  {{ formatTimestamp(scope.row.downtime)}}
                </span>
                 <span v-else> 未下架</span>
                    </template>
                </el-table-column>
                <el-table-column prop="goodsstatus" label="商品状态" width="200" align="center">
                  <template #default="scope">
                    <el-tag :type="scope.row.goodsstatus==='售卖中'?'success':'warning'">{{ scope.row.goodsstatus }}
                    </el-tag>
                  </template>
                </el-table-column>
              <el-table-column prop="views" label="浏览量" width="100" />
              <el-table-column label="操作" min-width="130" align="center">
                <template #default="scope">
                  <el-tooltip effect="dark" content="下架" >
                    <el-button text type="danger" @click="deleteGoods(scope.row.gid)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <br>
                  <el-tooltip effect="dark" content="同意" v-if="scope.row.status === '审核中'">
                    <el-button type="success" @click="agreeOrder(scope.row.gid)">
                      <el-icon>同意</el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip effect="dark" content="拒绝" v-if="scope.row.status === '审核中'">
                    <el-button type="error" @click="rejectOrder(scope.row.gid)">
                      <el-icon>拒绝</el-icon>
                    </el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
            <!--  分页-->
            <el-pagination
                    size="small"
                    background
                    layout="prev, pager, next"
                    :total="total"
                    v-model:currentPage="currentPage"
                    @current-change="handlePageChange"
                    class="mt-4"
            />
        </el-card>


    </div>    
</template>

<style scoped>
.el-breadcrumb{
  margin-bottom: 20px;
}

.searchbtn{
  float: right;
}
.icon-search{
  margin-right: 10px;
}
    .icon-search{
        margin-right: 10px;
        
    }

</style>